package com.tencent.qcloud.tim.uikit.modules.group.member;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.manor.common.utils.ClickUtil;
import com.manor.common.utils.StringUtil;
import com.manor.common.utils.ToastUtil;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMGroupMemberFullInfo;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.qcloud.tim.uikit.R;
import com.tencent.qcloud.tim.uikit.bean.RoleEvent;
import com.tencent.qcloud.tim.uikit.component.TitleBarLayout;
import com.tencent.qcloud.tim.uikit.component.dialog.GroupMemberDialog;
import com.tencent.qcloud.tim.uikit.component.dialog.TUIKitDialog;
import com.tencent.qcloud.tim.uikit.modules.group.info.GroupInfo;
import com.tencent.qcloud.tim.uikit.modules.group.interfaces.IGroupMemberLayout;
import com.tencent.qcloud.tim.uikit.utils.PopWindowUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import static com.tencent.qcloud.tim.uikit.modules.group.info.GroupInfoActivity.TYPE_MEMBER;


public class GroupMemberManagerLayout extends LinearLayout implements IGroupMemberLayout {

    private TitleBarLayout mTitleBar;
    private AlertDialog mDialog;
    private GroupMemberManagerAdapter mAdapter;
    private IGroupMemberRouter mGroupMemberManager;
    private GroupInfo mGroupInfo;
    private List<GroupMemberInfo> mGroupMembers = new ArrayList<>();
    private TextView tvSearch;
    private int mDataType = 0;


    public GroupMemberManagerLayout(Context context) {
        super(context);
        init();
    }

    public GroupMemberManagerLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public GroupMemberManagerLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        inflate(getContext(), R.layout.group_member_layout, this);
        tvSearch = findViewById(R.id.tvSearch);
        tvSearch.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                goSearch();
            }
        });
        mTitleBar = findViewById(R.id.group_member_title_bar);
        mTitleBar.setTitle("管理", TitleBarLayout.POSITION.RIGHT);
        mTitleBar.getRightIcon().setVisibility(GONE);
        mTitleBar.setOnRightClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mGroupInfo.isAdminOrOwner()) {
                    mGroupMemberManager.forwardDeleteMember(mGroupInfo);
                }
//                buildPopMenu();
//                mAdapter.notifyDataSetChanged();
            }
        });
        mAdapter = new GroupMemberManagerAdapter(R.layout.group_member_adpater_new,mGroupMembers);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                 if (mDataType == TYPE_MEMBER){
                     showSetAdmin(mGroupMembers.get(position));
                 }
            }
        });
        mAdapter.setMemberChangedCallback(new IGroupMemberChangedCallback() {

            @Override
            public void onMemberRemoved(GroupMemberInfo memberInfo) {
                mTitleBar.setTitle("群成员(" + mGroupInfo.getMemberDetails().size() + ")", TitleBarLayout.POSITION.MIDDLE);
            }
        });
        RecyclerView mRecycler = findViewById(R.id.mRecycler);
        mRecycler.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false));
        mRecycler.setAdapter(mAdapter);
    }

    public TitleBarLayout getTitleBar() {
        return mTitleBar;
    }

    public void setMDataType(int mDataType) {
        this.mDataType = mDataType;
    }

    @Override
    public void setParentLayout(Object parent) {

    }


    public void setDataSource(GroupInfo groupInfo) {
        mGroupInfo = groupInfo;
        mTitleBar.getRightGroup().setVisibility(mGroupInfo.isAdminOrOwner()? VISIBLE : INVISIBLE);
        if (mGroupInfo != null && mAdapter!=null){
            mGroupMembers.clear();
            mGroupMembers.addAll(mGroupInfo.getMemberDetails());

            mAdapter.notifyDataSetChanged();
        }
        if (groupInfo != null) {
            mTitleBar.setTitle("群成员(" + groupInfo.getMemberDetails().size() + ")", TitleBarLayout.POSITION.MIDDLE);
        }
    }

    private void  goSearch(){
        if (ClickUtil.canClick() && StringUtil.isListNotEmpty(mGroupMembers)) {
            GroupMemberDialog.Companion.load(getContext(),mGroupMembers);
        }
    }

    private void showSetAdmin(final GroupMemberInfo info ){
        final String groupId = mGroupInfo.getId();
        if (StringUtil.isEmpty(groupId))
            return;

        String name = info.getNameCard();
        if (StringUtil.isEmpty(name.trim())){
            name = info.getNickName();
        }
        new TUIKitDialog(getContext())
                .builder()
                .setCancelable(true)
                .setCancelOutside(true)
                .setTitle("您确认将"+name+"设置为管理员?")
                .setDialogWidth(0.75f)
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        V2TIMManager.getGroupManager()
                                .setGroupMemberRole(groupId,
                                        info.getUserId(),
                                        V2TIMGroupMemberFullInfo.V2TIM_GROUP_MEMBER_ROLE_ADMIN,
                                        new V2TIMCallback() {
                                            @Override
                                            public void onError(int i, String s) {
                                                ToastUtil.show("操作失败");
                                            }

                                            @Override
                                            public void onSuccess() {
                                                ToastUtil.show("修改成功");
                                                EventBus.getDefault().post(new RoleEvent(true));
                                               if (getContext() instanceof Activity){
                                                   ((Activity) getContext()).finish();
                                               }
                                            }
                                        });

                    }
                })
                .setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                })
                .show();
    }


    private void buildPopMenu() {
        if (mGroupInfo == null) {
            return;
        }
        if (mDialog == null) {
            mDialog = PopWindowUtil.buildFullScreenDialog((Activity) getContext());
            View moreActionView = inflate(getContext(), R.layout.group_member_pop_menu, null);
            moreActionView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mDialog.dismiss();
                }
            });
            Button addBtn = moreActionView.findViewById(R.id.add_group_member);
            addBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mGroupMemberManager != null) {
                        mGroupMemberManager.forwardAddMember(mGroupInfo);
                    }
                    mDialog.dismiss();

                }
            });
            Button deleteBtn = moreActionView.findViewById(R.id.remove_group_member);
            if (!mGroupInfo.isOwner()) {
                deleteBtn.setVisibility(View.GONE);
            }
            deleteBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (mGroupMemberManager != null) {
                        mGroupMemberManager.forwardDeleteMember(mGroupInfo);
                    }
                    mDialog.dismiss();
                }
            });
            Button cancelBtn = moreActionView.findViewById(R.id.cancel);
            cancelBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mDialog.dismiss();
                }
            });
            mDialog.setContentView(moreActionView);
        } else {
            mDialog.show();
        }

    }

    public void setRouter(IGroupMemberRouter callBack) {
        this.mGroupMemberManager = callBack;
    }

}
